"""目录规则数据模型"""

from pydantic import BaseModel, Field, field_validator, ConfigDict
from pathlib import Path
from typing import List, Optional, Dict, Any
from datetime import datetime


class DirectoryRule(BaseModel):
    """目录规则模型"""
    category: str = Field(..., description="主分类")
    subcategory: Optional[str] = Field(None, description="子分类")
    suggested_path: Path = Field(..., description="建议路径")
    confidence: float = Field(..., ge=0.0, le=1.0, description="置信度")
    keywords: List[str] = Field(default_factory=list, description="匹配关键词")
    date_based: bool = Field(default=False, description="是否基于日期")
    user_description: Optional[str] = Field(None, description="用户描述")
    reasoning: Optional[str] = Field(None, description="推理过程")
    alternative_paths: List[Path] = Field(default_factory=list, description="备选路径")
    created_at: datetime = Field(default_factory=datetime.now, description="创建时间")
    metadata: Dict[str, Any] = Field(default_factory=dict, description="额外元数据")

    model_config = ConfigDict(
        json_encoders={
            Path: str,
            datetime: lambda v: v.isoformat()
        }
    )

    @field_validator('confidence')
    @classmethod
    def validate_confidence(cls, v):
        """验证置信度范围"""
        if not 0.0 <= v <= 1.0:
            raise ValueError("置信度必须在0.0-1.0之间")
        return v

    @field_validator('category')
    @classmethod
    def validate_category(cls, v):
        """验证分类名称"""
        if not v or len(v.strip()) == 0:
            raise ValueError("分类名称不能为空")
        return v.strip()

    def get_full_path(self, base_path: Path) -> Path:
        """获取完整路径"""
        if self.suggested_path.is_absolute():
            return self.suggested_path
        return base_path / self.suggested_path

    def get_confidence_level(self) -> str:
        """获取置信度等级"""
        if self.confidence >= 0.9:
            return "高"
        elif self.confidence >= 0.7:
            return "中"
        elif self.confidence >= 0.5:
            return "低"
        else:
            return "很低"

    def add_alternative(self, path: Path) -> None:
        """添加备选路径"""
        if path not in self.alternative_paths:
            self.alternative_paths.append(path)

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "category": self.category,
            "subcategory": self.subcategory,
            "suggested_path": str(self.suggested_path),
            "confidence": self.confidence,
            "keywords": self.keywords,
            "date_based": self.date_based,
            "user_description": self.user_description,
            "reasoning": self.reasoning,
            "alternative_paths": [str(p) for p in self.alternative_paths],
            "created_at": self.created_at.isoformat(),
            "metadata": self.metadata
        }


class AnalysisContext(BaseModel):
    """分析上下文模型"""
    existing_structure: List[str] = Field(default_factory=list, description="现有目录结构")
    user_description: Optional[str] = Field(None, description="用户描述")
    user_preferences: Dict[str, Any] = Field(default_factory=dict, description="用户偏好")
    workspace_id: Optional[str] = Field(None, description="工作空间ID")
    complexity: str = Field(default="simple", description="任务复杂度: simple/medium/complex")
    batch_mode: bool = Field(default=False, description="是否批量模式")
    
    class Config:
        json_encoders = {
            datetime: lambda v: v.isoformat()
        }

    def add_existing_directory(self, path: str) -> None:
        """添加现有目录"""
        if path not in self.existing_structure:
            self.existing_structure.append(path)

    def set_complexity(self, file_count: int, has_description: bool) -> None:
        """设置任务复杂度"""
        if file_count == 1 and not has_description:
            self.complexity = "simple"
        elif file_count <= 5 and has_description:
            self.complexity = "medium"
        else:
            self.complexity = "complex"